<template>
  <div class="customer-list">
    <h1 class="title">客户列表</h1>
    <el-button type="primary" @click="showForm = true; isEditing = false; resetForm()" class="add-button">添加新客户</el-button>
    <el-table :data="customers" style="width: 100%" border v-if="!showForm">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="customer_name" label="姓名" width="180" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="contact" label="联系方式" width="180" />
      <el-table-column prop="address" label="地址" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <!-- 根据用户角色显示编辑和删除按钮 -->
          <el-button
            v-if="userRole === 'admin' || userRole === 'manager'"
            size="small"
            @click="editCustomer(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="userRole === 'admin' || userRole === 'manager'"
            size="small"
            type="danger"
            @click="deleteCustomer(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-form
      :model="customerForm"
      :rules="rules"
      ref="customerFormRef"
      label-width="100px"
      v-if="showForm"
    >
      <h2>{{ isEditing ? '编辑客户' : '添加新客户' }}</h2>
      <el-form-item label="姓名" prop="customer_name">
        <el-input v-model="customerForm.customer_name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="customerForm.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input v-model="customerForm.contact" placeholder="请输入联系方式"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="customerForm.address" placeholder="请输入地址"></el-input>
      </el-form-item>
      <div class="button-container">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="showForm = false; resetForm()">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { getCustomers, deleteCustomer, addCustomer, updateCustomer } from '@/api/customers';
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const customers = ref([]);
    const customerFormRef = ref(null);
    const showForm = ref(false);
    const isEditing = ref(false);
    const editingCustomerId = ref(null);
    const userRole = ref('user'); // 假设用户角色，实际应从后端获取

    const customerForm = ref({
      customer_name: '',
      email: '',
      contact: '',
      address: ''
    });

    const rules = {
      customer_name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度应为2-20个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ],
      contact: [
        { required: true, message: '请输入联系方式', trigger: 'blur' },
        { pattern: /^[0-9]{11}$/, message: '联系方式应为11位数字', trigger: 'blur' }
      ],
      address: [
        { required: true, message: '请输入地址', trigger: 'blur' },
        { min: 5, max: 100, message: '地址长度应为5-100个字符', trigger: 'blur' }
      ]
    };

    const fetchCustomers = async () => {
      try {
        const response = await getCustomers();
        customers.value = response.data;
      } catch (error) {
        console.error('Error fetching customers:', error);
      }
    };

    const deleteCustomerById = async (id) => {
      try {
        await deleteCustomer(id);
        fetchCustomers(); // 更新客户列表
      } catch (error) {
        console.error('Error deleting customer:', error);
      }
    };

    const editCustomer = (customer) => {
      showForm.value = true;
      isEditing.value = true;
      editingCustomerId.value = customer.id;
      // 填充表单数据
      Object.assign(customerForm.value, customer);
    };

    const submitForm = async () => {
      try {
        await customerFormRef.value.validate();
        if (isEditing.value) {
          // 更新客户
          await updateCustomer(editingCustomerId.value, customerForm.value);
        } else {
          // 添加新客户
          await addCustomer(customerForm.value);
        }
        console.log('操作成功');
        showForm.value = false;
        resetForm();
        fetchCustomers(); // 更新客户列表
      } catch (error) {
        console.error('Error submitting form:', error);
      }
    };

    const resetForm = () => {
      // 重置表单内容
      customerForm.value = {
        customer_name: '',
        email: '',
        contact: '',
        address: ''
      };
    };

    onMounted(async () => {
    // 从 localStorage 获取用户角色
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
      userRole.value = user.role;
    }

    await fetchCustomers(); // 获取客户列表
  });

    return {
      customers,
      customerForm,
      customerFormRef,
      rules,
      showForm,
      isEditing,
      userRole,
      deleteCustomer: deleteCustomerById,
      editCustomer,
      submitForm,
      resetForm,
    };
  }
};
</script>

<style scoped>
.customer-list {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.add-button {
  margin-bottom: 20px;
}

.el-table {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.el-table th.el-table__cell {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: bold;
  text-align: center !important; /* 使表头内容居中 */
}

.el-table th.el-table__cell > .cell {
  padding: 12px 0;
}

.el-table td.el-table__cell {
  vertical-align: middle;
}

.el-table .cell {
  text-align: center; /* 使表格内容居中 */
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.button-container {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.el-form {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 20px;
}
</style>